#include "ProfilerWin.h"

CProfilerWin::CProfilerWin(void)
{
}

CProfilerWin::~CProfilerWin(void)
{
}

bool CProfilerWin::init(void)
{
	BOOL result = QueryPerformanceFrequency(&m_frequency);
	if(result == TRUE)
		return true;
	else
		return false;

}

void CProfilerWin::startApplication(void)
{
	QueryPerformanceCounter(&(m_allApplication.startTime));
	m_allApplication.numberOfExecution = 1;
	m_allApplication.executionTime=0;
}

void CProfilerWin::endApplication(void)
{
	//get the final time
	QueryPerformanceCounter(&(m_allApplication.endTime));

	//add the execution time
	m_allApplication.executionTime = m_allApplication.endTime.QuadPart - m_allApplication.startTime.QuadPart;
}

void CProfilerWin::startCount(const string& name)
{
	//check if the entry alrady exist
	for(map<string, timeStruct>::iterator i = m_timeMap.begin(); i!=m_timeMap.end(); i++)
	{
		if(i->first.compare(name)==0) //if it exist
		{
			//get the new start time
			QueryPerformanceCounter(&(i->second.startTime));

			//increase the number of execution
			i->second.numberOfExecution++;
			return;
		}
	}

	//it doesn't exist so we create it in the map
	timeStruct newTimeStruct;
	newTimeStruct.endTime.QuadPart=0;
	newTimeStruct.startTime.QuadPart=0;
	newTimeStruct.numberOfExecution=1;
	newTimeStruct.executionTime=0;


	//add an entry in the map
	m_timeMap[name]=newTimeStruct;

	//get the start time
	QueryPerformanceCounter(&(m_timeMap[name].startTime));
	
}

void CProfilerWin::endCount(const string& name)
{
	for(map<string, timeStruct>::iterator i = m_timeMap.begin(); i!=m_timeMap.end(); i++)
	{
		if(i->first.compare(name)==0) 
		{
			QueryPerformanceCounter(&(i->second.endTime));
			i->second.executionTime+=i->second.endTime.QuadPart - i->second.startTime.QuadPart;
			return;
		}
	}
}

void CProfilerWin::write(void)
{
	//display the time of the total application
	double realApplicationTime = m_allApplication.executionTime/(double)m_frequency.QuadPart;
	printf("Overall : %13.9f \n", realApplicationTime);

	//display info about functions
	for(map<string, timeStruct>::iterator i = m_timeMap.begin(); i!=m_timeMap.end(); i++)
	{
		printf(i->first.c_str());
		double realTime = i->second.executionTime/(double)m_frequency.QuadPart;
		printf(" : %13.9f \n", realTime);
		printf("    - Percentage of total execution = ");
		double percent = realTime/realApplicationTime*100;
		printf("%5.3f\n", percent);
		printf("    - Number of call : %d\n", i->second.numberOfExecution);

	}
}